package com.miraclesea.test.database.module;

import org.dbunit.database.DatabaseConfig;
import org.unitils.core.UnitilsException;
import org.unitils.dbunit.DbUnitModule;
import org.unitils.dbunit.util.DbUnitDatabaseConnection;

import com.google.common.base.Strings;

public final class ExtDbUnitModule extends DbUnitModule {
	
	private static final String DATABASE_TYPE = "DbUnitModule.database.type";

	@Override
	public DbUnitDatabaseConnection getDbUnitDatabaseConnection(final String schemaName) {
		DbUnitDatabaseConnection result = dbUnitDatabaseConnections.get(schemaName);
		if (null != result) {
			return result;
		}
		result = super.getDbUnitDatabaseConnection(schemaName);
		String databaseType = configuration.getProperty(DATABASE_TYPE);
		if (Strings.isNullOrEmpty(databaseType)) {
			throw new UnitilsException(String.format("No value found for property %s", DATABASE_TYPE));
		}
		SupportedDatabaseType supportedDatabaseType;
		try {
			supportedDatabaseType = SupportedDatabaseType.valueOf(databaseType);
		} catch (final IllegalArgumentException ex) {
			throw new UnitilsException(String.format("Unable to find a enum value in enum: %s, with value name: %s", SupportedDatabaseType.class, databaseType));
		}
		result.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, supportedDatabaseType.getDataTypeFactory());
		if (null != supportedDatabaseType.getMetadataHandler()) {
			result.getConfig().setProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER, supportedDatabaseType.getMetadataHandler());
		}
		return result;
	}
}
